<template>
  <div>
    <Dialog class="wide-popup setUp" title="调拨申请" :loading="loading" :visible="visible" :reveal="true" @close="handleClose" @confirm="balanceSubmit">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="70px" class="demo-ruleForm">
        <el-form-item label="调出仓库" prop="calloutWriteoffId">
          <el-select v-model="ruleForm.calloutWriteoffId" filterable placeholder="请选择" style="width: 237.5px" @change="idChange">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="调入仓库" prop="mediatorWriteoffId">
          <el-select v-model="ruleForm.mediatorWriteoffId" filterable placeholder="请选择" style="width: 237.5px" @change="idChange">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <div class="detailedlist">挑选</div>
        <GetProductContent ref="GetProductContent" :is-commonly-used="true" :warehouse-id="ruleForm.warehouseId" :tabs-text="tabsText" @listChange="listChange" />
      </el-form>
      <div v-if="selectTables.length>0" class="setUp">
        <span class="detailedlist">调拨清单</span>
        <el-table :data="selectTables" class="borders">
          <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="类型" prop="productAttrib" :show-overflow-tooltip="true" />
          <el-table-column label="规格" prop="spec" :show-overflow-tooltip="true" />
          <el-table-column label="单位" prop="unit" :show-overflow-tooltip="true" />
          <el-table-column label="售价" prop="sellPrice" :show-overflow-tooltip="true" />
          <el-table-column label="可用库存" prop="availableStock" :show-overflow-tooltip="true" />
          <el-table-column label="开单数量" min-width="120">
            <template slot-scope="{ row }">
              <el-input-number v-model="row.billNum" style="width:100px" controls-position="right" :min="row.availableStock === '0' ? 0 : 1" :max="row.availableStock - 0" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button type="text" @click="deteleHandle(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </Dialog>
  </div>
</template>

<script>
// import { mapMutations } from 'vuex';
import GetProductContent from "@/components/getProductContent";
import Dialog from "@/components/Dialog";
import { warehouseList } from "@/utils/common";
export default {
  name: "Index",
  components: {
    GetProductContent,
    Dialog,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tabsText: [
        { label: "物品", name: "goods" },
        { label: "药品", name: "drugs" },
      ],
      ruleForm: {},
      rules: {
        calloutWriteoffId: [
          // 主要需求
          { required: true, message: "请选择调出仓库", trigger: "change" },
        ],
        mediatorWriteoffId: [
          { required: true, message: "请选择调入仓库", trigger: "change" },
        ],
      },
      option: [],
      selectTables: [],
      loading: false,
      depositAmount: 0,
      balancePayment: 0,
      warehouseList: [],
    };
  },
  mounted() {
    this.userId = this.$store.getters.currentUserInfo.id;
    this.warehouseList = warehouseList();
  },
  methods: {
    componentBalance() {
      this.depositAmount = this.depositAmount.replace(/[^\d.]/g, ""); // 清除“数字”和“.”以外的字符
      this.depositAmount = this.depositAmount.replace(/^\./g, ""); // 验证第一个字符是数字而不是.
      this.depositAmount = this.depositAmount.replace(/\.{2,}/g, "."); // 只保留第一个. 清除多余的
      this.depositAmount = this.depositAmount
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      this.depositAmount = this.depositAmount.replace(
        /^(\-)*(\d+)\.(\d\d).*$/,
        "$1$2.$3"
      ); // 只能输入两个小数
      this.balancePayment =
        ((Number(this.allPrice) - Number(this.depositAmount)).toFixed(2) *
          100) /
        100;
    },
    listChange(list) {
      const lists = JSON.parse(JSON.stringify(list));
      console.log(lists);
      // 给selectTables添加新增的数据
      lists.forEach(item => {
        let isTrue = false;
        this.selectTables.forEach(json => {
          if (item.id === json.id) {
            isTrue = true;
          }
        });
        if (!isTrue) {
          this.$set(item, 'billNum', item.availableStock === '0' ? 0 : 1);
          this.selectTables.push(item);
        }
      });
      // 删除已取消勾选的数据
      for (let i = 0; i < this.selectTables.length; i++) {
        const item = this.selectTables[i];
        let isTrue = false;
        for (let n = 0; n < lists.length; n++) {
          if (item.id === lists[n].id) {
            isTrue = true;
          }
        }
        if (!isTrue) {
          this.selectTables.splice(i, 1);
          i--;
        }
      }
    },
    async deteleHandle(items) {
      const confirmResult = await this.$confirm("请确认是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        this.$nextTick(function() {
          this.$refs.GetProductContent.deteleContent(items.id);
        });
      }
    },
    async balanceSubmit() {
      if (!this.ruleForm.warehouseId) {
        this.$message.error("请选择仓库");
        return;
      }
      if (this.selectTables.length === 0) {
        this.$message.error("请选择商铺");
        return;
      }
      let isTrue = true;
      let msg = "";
      this.selectTables.forEach(item => {
        if (parseInt(item.billNum) === 0) {
          isTrue = false;
          msg = "开单数量不能为0";
        }
        if (parseInt(item.billNum) > parseInt(item.availableStock)) {
          isTrue = false;
          msg = "开单数量不能大于库存数量";
        }
      });
      if (!isTrue) {
        this.$message.error(msg);
        return;
      }
      this.loading = true;
      const allotDetailDto = [];
      this.selectTables.forEach(item => {
        const json = {
          allotNumber: item.billNum,
          materialMedicineId: item.id,
          materialMedicineName: item.name,
          type: item.productAttrib,
        };
        allotDetailDto.push(json);
      });
      const res = await this.$api['warehouse/allocation/addAllotrecord']({ ...this.ruleForm, allotDetailDto: allotDetailDto });
      this.loading = false;
      if (res.code !== 200) this.$message.error(res.msg);
      this.$message.success("新增调拨成功");
      this.$emit("successHandle");
    },
    handleClose() {
      this.$emit('handleClose');
    },
    idChange() {
      if (this.ruleForm.calloutWriteoffId && this.ruleForm.mediatorWriteoffId) {
        let operatorIds1 = '';
        let operatorIds2 = '';
        this.warehouseList.forEach(item => {
          if (item.id === this.ruleForm.calloutWriteoffId) {
            this.ruleForm.calloutWriteoffName = item.name;
            operatorIds1 = item.operatorIds;
          }
          if (item.id === this.ruleForm.mediatorWriteoffId) {
            this.ruleForm.mediatorWriteoffName = item.name;
            operatorIds2 = item.operatorIds;
          }
        });
        if (!this.userId) this.userId = this.$store.getters.currentUserInfo.id;
        if (operatorIds1.indexOf(this.userId) > -1 || operatorIds2.indexOf(this.userId) > -1) {
          this.ruleForm.warehouseId = this.ruleForm.calloutWriteoffId;
        } else {
          this.$message.error("调出、调入其中一方必须是操作员为自己的仓库");
          this.ruleForm.warehouseId = '';
        }
      }
    },
  },
};
</script>

<style scoped lang='scss'>
.borders .el-table .cell{
  height: 32px !important;
}
.detailedlist{
  display: block;
  font-size: 16px;
  margin-bottom: 10px;
}
/deep/.el-table .cell{
  line-height: 30px !important;
}
</style>
